package com.todod.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * js执行
 *
 * @author gsh
 * @version 1.0
 * @date 2021/4/20 0020 10:25
 */
@Slf4j
public class JavaScriptUtil {

    public static Object jsonValue( String format,  Object data) throws Exception {

        String script ="function jsonValue(dataKey, data) {\n" +
                "    data = JSON.parse(data)\n" +
                "    var dataKeys = dataKey.split('.')\n" +
                "\n" +
                "    for (var i = 0; i < dataKeys.length; i++) {\n" +
                "        var e = dataKeys[i]\n" +
                "        data = data[e]\n" +
                "    }\n" +
                "    data = JSON.stringify(data)\n"+
                "    return data\n" +
                "}";

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        engine.eval(script);
        Invocable inv = (Invocable) engine;
        // 执行obj对象的名为hello的方法
        Object rdata = inv.invokeFunction("jsonValue",format, data);
        return rdata;
    }

    public static void main(String[] args) throws Exception {
        String data = "{\"code\":20000,\"data\":{\"data\":[{\"bw_report_dimension\":\"Germany\",\"bw_report_value\":{\"bw_report_dimension\":\"Germany\",\"bw_report_value\":400.00}},{\"bw_report_dimension\":\"Australia\",\"bw_report_value\":400.00},{\"bw_report_dimension\":\"Spain\",\"bw_report_value\":850.00},{\"bw_report_dimension\":\"Canada\",\"bw_report_value\":1500.00},{\"bw_report_dimension\":\"Chile\",\"bw_report_value\":1600.00},{\"bw_report_dimension\":\"Denmark\",\"bw_report_value\":1800.00},{\"bw_report_dimension\":\"England\",\"bw_report_value\":2000.00},{\"bw_report_dimension\":\"USA\",\"bw_report_value\":2200.00},{\"bw_report_dimension\":\"Norway\",\"bw_report_value\":22000.00},{\"bw_report_dimension\":\"New Zealand\",\"bw_report_value\":2500.00}]},\"msg\":\"ok\"}";
        Object d = jsonValue("data.data", data);
        System.out.println(d.toString());
    }
}
